package com.markerhub.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.dto.CollegeDto;
import com.markerhub.common.lang.Const;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.SysCollege;
import com.markerhub.entity.SysMajor;
import com.markerhub.entity.SysUser;
import com.markerhub.service.SysCollegeService;
import com.markerhub.service.impl.SysCollegeServiceImpl;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wang
 * @since 2022-03-31
 */
@RestController
@RequestMapping("/sys/college")
public class SysCollegeController extends BaseController {

    @GetMapping("/list")
    public Result list(String username){
        List<SysCollege> pageData = sysCollegeService.list(new QueryWrapper<SysCollege>()
                .like(StrUtil.isNotBlank(username), "username", username));
        pageData.forEach(u ->{
            u.setSysMajors(sysMajorService.listMajorsByCollegeId(u.getId()));
        });
        return Result.succ(pageData);
    }

    @PostMapping("/save")//管理员录入学院信息
    public Result save(@Validated @RequestBody SysCollege sysCollege) {
        SysCollege sys=null;
        sys=sysCollegeService.getObject(sysCollege.getCollege());
        if(sys!=null){
            return Result.fail("学院已存在");
        }else {
            sysCollegeService.save(sysCollege);

            return Result.succ(sysCollege);
        }
    }

    @PostMapping("/delete")//删除学院信息
    public Result delete(@RequestBody SysCollege sysCollege){

       List<SysMajor> pageData = sysMajorService.list( new QueryWrapper<SysMajor>()
                .eq( "college_id", sysCollegeService.getIdByCollege(sysCollege.getCollege())));
        if(!pageData.isEmpty()){
            return Result.fail("该学院的专业不为空");
        }else{
            SysCollege sys = sysCollegeService.getIdByColleg(sysCollege.getCollege());
            sysCollegeService.removeById(sys.getId());
            return Result.succ("");
        }
    }

    @PostMapping("/update")//修改学院的名字
    public Result update(@Validated @RequestBody CollegeDto collegeDto){
        SysCollege sys=null;
        sys=sysCollegeService.getObject(collegeDto.getNewName());
        if(sys!=null){
            return Result.fail("学院名重复");
        }else{
            SysCollege sysCollege=sysCollegeService.getByCollegeNme(collegeDto.getOldName());
            sysCollege.setCollege(collegeDto.getNewName());
            sysCollegeService.updateById(sysCollege);
            return Result.succ("");
        }
    }

}
